<template>
  <div class="container-xl my-home-div" :style="{ '--bs-gutter-x': 0, '--my-home-div-height': '56px' }">
    <div class="row my-home-div-line">
      <div class="col">
        <svg class="icon" aria-hidden="true">
          <use xlink:href="#icon-icon_team_Settings"></use>
        </svg> 团队设置
      </div>
    </div>
    <div class="row">
      <div class="col">
        <div :style="{ padding: '12px' }">
          <el-tabs tab-position="left" v-model="active">
            <el-tab-pane class="pl-4 pr-4" name="1" label="基本设置">
              <el-form ref="formref" :rules="rules" :model="form" label-width="80px" :form="form" label-position="left">
                <el-form-item label="团队名称" prop="name">
                  <el-input v-model="form.name"></el-input>
                </el-form-item>
                <el-form-item label="团队介绍">
                  <el-input type="textarea" rows="10" placeholder="团队介绍会向外公开" v-model="form.info"></el-input>
                </el-form-item>
                <el-form-item label="团队展示个人题目" label-width="280px" prop="name">
                  <el-radio-group v-model="form.allowquestion">
                    <el-radio :label="0">所有成员</el-radio>
                    <el-radio :label="1">教师管理员</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="团队展示个人题单" label-width="280px" prop="name">
                  <el-radio-group v-model="form.allowquestionbank">
                    <el-radio :label="0">所有成员可贡献</el-radio>
                    <el-radio :label="1">仅教师管理员可贡献</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="团队测评记录源码学生是否可见" label-width="280px" prop="name">
                  <el-radio-group v-model="form.iscode">
                    <el-radio :label="true">否</el-radio>
                    <el-radio :label="false">是</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="团队测评记录是否展示老师和管理员记录" label-width="280px" prop="name">
                  <el-radio-group v-model="form.isadminshowquestion">
                    <el-radio :label="false">否</el-radio>
                    <el-radio :label="true">是</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="团队比赛记录是否展示老师和管理员记录" label-width="280px" prop="name">
                  <el-radio-group v-model="form.isadminshowactivity">
                    <el-radio :label="false">否</el-radio>
                    <el-radio :label="true">是</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="团队排行榜是否展示老师和管理员数据" label-width="280px" prop="name">
                  <el-radio-group v-model="form.isranking">
                    <el-radio :label="true">否</el-radio>
                    <el-radio :label="false">是</el-radio>
                  </el-radio-group>
                </el-form-item>

                <el-form-item label="团队练习数据是否展示学生自建题目的练习数据" label-width="350px" prop="name">
                  <el-radio-group v-model="form.isruserquestion">
                    <el-radio :label="false">否</el-radio>
                    <el-radio :label="true">是</el-radio>
                  </el-radio-group>
                </el-form-item>

                <el-form-item>
                  <el-button type="primary" @click="change">保存</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane name="课程配置" class="pl-4 pr-4" label="课程配置">
              <el-form :model="form" label-width="80px">
                <el-form-item label="课程配置">
                  <el-checkbox-group v-model="courses">
                    <el-checkbox :label="20">C++语言基础</el-checkbox>
                    <el-checkbox :label="21">普及组L1</el-checkbox>
                    <el-checkbox :label="22">普及组L2</el-checkbox>
                    <el-checkbox :label="23">提高组L1</el-checkbox>
                    <el-checkbox :label="24">提高组L2</el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
                <el-form-item label="">
                  <el-button type="primary" @click="submitupdateteamcoursegroup">保存</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane name="2" class="pl-4 pr-4" label="成员管理">
              <el-form ref="formref1" :rules="rules" :model="form" label-width="80px">
                <el-form-item label="成员审核">
                  <el-radio-group v-model="form.inuser">
                    <el-radio class="radio " label="search">需要审核才能加入</el-radio>
                    <el-radio label="open" class="radio ">无需审核即可加入</el-radio>
                    <el-radio label="close" class="radio ">不可被搜索到，只可由管理员主动邀请加入</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="邀请成员">
                  <el-form label-width="80px" label-position="top">
                    <div>
                      <el-form-item label="方式一：向已注册的用户发站内信" class="pb-3">
                        <el-input v-model="usert" placeholder="输入用户的ID或者已注册手机号" :style="{ width: '70%' }" class="mr-3">
                        </el-input>
                        <el-button @click="addteamuser">发送邀请</el-button>
                      </el-form-item>
                    </div>
                    <div>
                      <el-form-item label="方式二：二维码邀请">
                        <el-button @click="shouimage">获取团队验证码</el-button>
                        <div class="el-error">说明：二维码可以发给未注册用户，用户接受邀请并注册后自动加入当前团队</div>
                      </el-form-item>
                    </div>
                  </el-form>
                </el-form-item>
                <el-form-item label="成员列表">
                  <div>
                    <div class="wfz1">管理员</div>
                    <el-row>
                      <el-col v-for="t in admins" :key="'a' + t.ID" :span="3">
                        <el-button class="el-button-text" text @click="changeuser(t)">{{ t.user?.name
                          }}</el-button>
                      </el-col>
                    </el-row>
                  </div>
                  <div v-for="(v, k) in group" :key="'=' + k">
                    <div class="wfz1">
                      {{ v.name }}
                      <span class="span" @click="onSubmit(v.ID)" v-show="k">编辑组名</span>
                      <span class="span" @click="delgroup(Number(v.ID))" v-show="k">删除组</span>
                      <!-- <span class="span" v-show="k">下移</span>
                    <span class="span" v-show="k">上移</span>-->
                    </div>
                    <el-row>
                      <el-col v-for="t in v.teamuser" :key="t.ID" :span="3">
                        <el-button class="el-button-text" text @click="changeuser(t)">{{ t.user?.name
                          }}</el-button>
                      </el-col>
                    </el-row>
                  </div>
                </el-form-item>
                <el-form-item label="">
                  <el-button @click="onSubmit()">+ 添加分组</el-button>
                </el-form-item>
                <el-form-item>
                  <!-- <el-button type="primary" @click="">保存</el-button> -->
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane name="3" label="申请审核">
              <template #label>
                <!-- badge?.sett -->
                <el-badge is-dot :style="{ left: '3px' }" :hidden="hiddenBadge"></el-badge>申请审核
              </template>

              <div>
                <table class="table">
                  <thead class="thead-light">
                    <tr>
                      <th scope="col">申请人</th>
                      <th scope="col">申请原因</th>
                      <th scope="col">昵称</th>
                      <th scope="col">操作</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr v-for="t in inusers" :key="t.ID">
                      <td class="pt-0 pb-0">{{ t.user?.name }}</td>
                      <td class="pt-0 pb-0">{{ t.context }}</td>
                      <td class="pt-0 pb-0">{{ t.username }}</td>
                      <td class="pt-0 pb-0">
                        <el-button text v-show="t.jurisdiction == '1'" @click="changeteamuser(t, '0')">
                          <el-icon>
                            <Check />
                          </el-icon>通过
                        </el-button>
                        <el-button text v-show="t.jurisdiction == '1'" @click="changeteamuser(t, '3')">
                          <el-icon>
                            <Close />
                          </el-icon>拒绝
                        </el-button>
                        <el-button v-show="t.jurisdiction == '0'" text>已通过</el-button>
                        <el-button v-show="t.jurisdiction == '3'" text>已拒绝</el-button>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </el-tab-pane>
            <el-tab-pane class="pl-4 pr-4" name="5" label="其他">
              <br />
              <div>
                <el-button @click="delteam">解散团队</el-button>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>

      </div>
    </div>

    <el-dialog class="dialog1" title="设置成员" v-model="dialogVisible" width="500px">
      <el-form style="padding-left: 20px; padding-right: 20px" ref="formuserref" :model="formuser" label-width="100px">
        <el-form-item label="成员账号：">{{ formuser.user?.name }}</el-form-item>
        <el-form-item label="所属小组：">
          <el-select v-model="formuser.teamusergroupid" placeholder="请选择所属小组">
            <el-option v-for="(v, i) in data?.teamusergroup" :key="'2' + i" :label="v.name" :value="Number(v.ID)">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="formuser.isAdmin" placeholder="请选择角色">
            <el-option v-for="(v, i) in [
              { data: 0, value: '普通成员' },
              { data: 2, value: '教师' },
              { data: 1, value: '管理员' },
            ]" :key="'2_' + i" :label="v.value" :value="v.data"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="row">
          <div class="col text-left">
            <el-button @click="delteamuser">移除成员</el-button>
          </div>
          <div class="col">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="changeteamuser(formuser, '0', '修改')">确 定</el-button>
          </div>
        </div>
      </template>
    </el-dialog>
    <el-dialog class="image-dialog1" title="二维码" v-model="dialogVisibleimage" width="400px">
      <img id="canvasimage" width="400" />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { Check, Close } from '@element-plus/icons-vue';
import { ElForm, ElMessage, ElMessageBox } from "element-plus";
import QRCode from 'qrcode';
import {
  computed,
  onMounted,
  reactive,
  ref,
  toRaw,
  watch,
} from "vue";
import { useRouter } from "vue-router";
import { Teamuser } from "../../../admin/views/data";
import { teamrules } from "../../../admin/views/data/formrules";
import {
  asyncdelteam,
  asyncdelteamgroup,
  asyncselectteamcoursegroup,
  asyncteamaddteamgroup,
  asyncteamadminaddteamuser,
  asyncteamchangeteamuser,
  asyncteamcreateorupdatenotice,
  asyncteamdelteamuser,
  asyncupdateteamcoursegroup,
} from "../../../api";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import mergeImages from '../../../util/merge-images';
import { badgeType } from "./type";
interface PU {
  data?: Studycodemodel.Iteam,
  changeteam?: (str: Studycodemodel.Iteam) => void,
  isAdmin?: 0 | 1 | 2
  user?: Studycodemodel.Iuser
  teamusers?: Studycodemodel.Iteamuser[]
  getUsers?: Function
  badge?: badgeType
}
const p = defineProps<{
  data?: Studycodemodel.Iteam,
  changeteam?: (str: Studycodemodel.Iteam) => void,
  isAdmin?: 0 | 1 | 2
  user?: Studycodemodel.Iuser
  teamusers?: Studycodemodel.Iteamuser[]
  getUsers?: Function
  badge?: badgeType
}>()
const inusers = computed(() => {
  // 先判断 teamusers 是否存在并返回数组
  const users = p.teamusers || [];
  // 使用 sort 对 users 按照 jurisdiction 字段排序
  return users.sort((a, b) => {
    // 如果 a 或 b 的 jurisdiction 为 1 或 2，排在前面
    const isAValid = a.jurisdiction === "1" || a.jurisdiction === "2";
    const isBValid = b.jurisdiction === "1" || b.jurisdiction === "2";
    if (isAValid && !isBValid) return -1; // a 在前
    if (!isAValid && isBValid) return 1;  // b 在前
    return 0; // 不动
  });
});


const hiddenBadge = computed(() => {
  return !inusers.value.some(e => e.jurisdiction === '1' || e.jurisdiction === '2')
})

const form = reactive(Object.assign({}, toRaw(p.data)));
const formref = ref<typeof ElForm>();
const rules = teamrules;
const usert = ref<number | string>("");
const dialogVisible = ref(false);
const dialogVisibleimage = ref(false);
const router = useRouter();
const active = ref<"1" | "2" | "3" | "4">("1");
const group = computed(() => {
  const t = p.data;
  let n: Studycodemodel.Iteamusergroup[] = [];
  if (t) {
    const g = t.teamusergroup || [];
    n = g.map((e) => {
      let teamuser: Studycodemodel.Iteamuser[] = [];
      if (p.teamusers) {
        teamuser = p.teamusers.filter((v) => v.teamusergroupid === e.ID);
      }
      return {
        ...e,
        teamuser,
        name: "分组：" + e.name,
      };
    });
  }
  const o: Studycodemodel.Iteamusergroup = {
    name: "未分组",
    teamuser:
      p.teamusers?.filter(
        (e) => e.jurisdiction === "0" && !e.teamusergroupid
      ) || [],
  };
  return [o].concat(n);
});

const admins = computed<Studycodemodel.Iteamuser[]>(() => {
  const d = p.teamusers?.filter((e) => e.isAdmin === 1) || [];
  return d;
});

async function addteamuser() {
  try {
    if (p.data?.ID) {
      const [data] = await asyncteamadminaddteamuser({
        teamid: p.data.ID,
        name: usert.value,
      });
      if (data.userid) {
        const d = await asyncteamcreateorupdatenotice({
          teamid: p.data.ID,
          users: [data.userid],
          context: `【${p.data.name}】团队邀请你加入`,
          name: `【${p.data.name}】团队邀请你加入`,
        });
        await asyncteamcreateorupdatenotice(
          Object.assign(d, {
            description: `/#/mydata/myaddteam/${d.ID}?teamid=${p.data.ID}`,
          })
        );
      }
      ElMessage.success("邀请成功");
    }
  } catch (e: any) {
    ElMessage.error(e);
  }
}
async function change() {
  if (p.isAdmin === 1) {
    if (p.changeteam) await p.changeteam(form);
    Object.assign(form, toRaw(p.data));
    ElMessage.success('修改成功')
  }
}

function shouimage() {
  dialogVisibleimage.value = true;
  'https://cdn.hterobot.com/vue/public/favicon.ico'


  setTimeout(() => {
    QRCode.toDataURL(`https://oj.hterobot.com/h51.html?teamid=${p.data?.ID}`, {
      type: 'image/png',
      width: 500,

    },
      async (err, url) => {
        const mig = await fetch('https://cdn.hterobot.com/JOY/jointeam_bc.png')
        const n = await mig.blob()
        const fileReader = new FileReader()
        fileReader.readAsDataURL(n)
        fileReader.onloadend = (e) => {
          var result = e.target?.result as string
          mergeImages([{ src: result }, { src: url, x: 250, y: 750 }, { src: String(p.data?.name), format: 'text', fontSize: '50px', color: '#fff', x: 150, y: 400 }, { src: `欢迎你的加入！`, fontSize: '80px', color: '#fff', x: 150, y: 520, format: 'text' }, , { src: '扫码注册 自动加入团队', fontSize: '48px', color: '#fff', x: 250, y: 700, format: 'text' }], {
            width: 1000,
            height: 1778,
          }).then(e => {
            const canvasimage = document.getElementById("canvasimage") as HTMLImageElement
            if (canvasimage) {
              canvasimage.src = e as string
            }
          })
        }

      }
    )
  }, 100);
}

const courses = ref<any[]>([])
function selectteamcoursegroup() {
  asyncselectteamcoursegroup({ teamid: p.data?.ID }).then(e => {
    courses.value = e.rows.map(e => e.coursegroupid)
  })
}

function submitupdateteamcoursegroup() {
  asyncupdateteamcoursegroup({ teamid: Number(p.data?.ID), courses: courses.value }).then(e => {
    ElMessage.success("保存成功");
  }).catch(f => {
    ElMessage.error(f);
  })
}

onMounted(() => {
  if (p.isAdmin !== 1) {
    ElMessage.error("没有权限");
    router.push("/");
  }
  selectteamcoursegroup()
});

watch(
  () => active.value,
  (e) => {
    if (e === "3") {
      if (p.getUsers) p.getUsers();
    }
  }
);

watch(
  () => p.isAdmin,
  (t) => {
    if (!t) {
      ElMessage.error("没有权限");
      router.push("/");
    }
  }
);

async function changeteamuser(
  t: Studycodemodel.Iteamuser,
  str: Studycodemodel.Iteamuser["jurisdiction"],
  msg?: string
) {
  let n = "添加";
  switch (str) {
    case "0":
      n = "添加";
      break;
    case "1":
      n = "申请";
      break;
    case "2":
      n = "邀请";
      break;
    case "3":
      n = "拒接";
      break;
  }
  if (msg) {
    n = msg;
  }
  if (p.isAdmin === 1) {
    // ElMessageBox.confirm(`确定要${n}`, n, {
    //   confirmButtonText: "确定",
    //   cancelButtonText: "取消",
    //   type: "warning",
    // }).then(async (e) => {
    const d = toRaw(t);
    d.jurisdiction = str;
    await asyncteamchangeteamuser(d);
    if (p.getUsers) await p.getUsers();
    dialogVisible.value = false;
    ElMessage.success("保存成功");
    Object.assign(formuser, Teamuser);
    // });
  } else {
    ElMessage.warning("团队管理员才有权限修改");
  }
}

function changeuser(t: Studycodemodel.Iteamuser) {
  Object.assign(formuser, t);
  dialogVisible.value = true;
}

async function onSubmit(ID?: number) {
  ElMessageBox.prompt("请输入名称", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
  })
    .then(async ({ value }) => {
      if (!value) return;
      await asyncteamaddteamgroup({
        ID,
        teamid: p.data?.ID,
        name: value,
        // description: ['动态', '题单', '题目', '通知', '']
      });
      if (p.changeteam && p.data) p.changeteam({ ID: p.data.ID });
    })
    .catch((e: any) => {
      console.log(e);
    });
}
const formuser = reactive(Object.assign({}, Teamuser));

async function delgroup(ID: number) {
  ElMessageBox.confirm("确定要删除此组吗", "删除", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    if (ID && p.data && p.data.ID) {
      await asyncdelteamgroup({ ID, teamid: p.data.ID });
      if (p.changeteam) await p.changeteam({ ID: p.data.ID });
    }
  });
}

async function delteamuser() {
  ElMessageBox.confirm("确定要移除此团员吗", "删除", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      if (formuser.ID && p.data && p.data.ID) {
        await asyncteamdelteamuser({ ID: formuser.ID, teamid: p.data?.ID });
        if (p.getUsers) await p.getUsers();
        dialogVisible.value = false;
        ElMessage.success("移除成功");
        Object.assign(formuser, Teamuser);
      }
    })
    .catch((e: any) => {
      console.log(e);
    });
}

async function delteam() {
  ElMessageBox.confirm("确定要解散此团队吗", "删除", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      if (p.data?.user?.ID === p.user?.ID && p.data?.ID) {
        await asyncdelteam({ ID: p.data.ID, teamid: p.data.ID });
        location.href = "/";
      }
    })
    .catch((e: any) => {
      console.log(e);
    });
}

</script>

<style scoped>
.radio {
  display: block;
  height: 40px;
  line-height: 40px;
}

.span {
  font-size: 14px;
}

.wfz {
  line-height: 40px;
}

.wfz1 {
  line-height: 40px;
  font-weight: 600;
}

.wfz1 span {
  display: inline-block;
  margin-left: 30px;
  cursor: pointer;
  font-weight: 400;
  color: #888;
}

.wfz1 span:hover {
  color: var(--color-cheng);
}

.tab td {
  line-height: 26px;
}

tbody td {
  line-height: 41px;
}

tbody th {
  line-height: 41px;
}

#canvasimage {
  object-fit: cover;
}

.canvasimage2 {
  width: 80px;
  padding-top: 20px;
}
</style>

<style>
.dialog1 .el-dialog__header {
  padding-left: 40px;
  padding-right: 40px;
}

.dialog1 .el-dialog__footer {
  padding-left: 40px;
  padding-right: 40px;
}

.image-dialog1 .el-dialog__header {
  display: none;
}

.image-dialog1 .el-dialog__body {
  padding: 0;
}

.image-dialog1 {
  --el-dialog-bg-color: rgba(0, 0, 0, 0) !important;
}

.el-button-text {
  max-width: 123px;
  overflow: hidden;
}

.el-button-text span {
  width: 99px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>